#include "sprintf.h"

static char digits[] = "0123456789abcdef";

// 将字符写入缓冲区
static int
print_number_to_buf(long long num, int base, int sign, char *buf, int *index)
{
  char local_buf[20];
  int i;
  unsigned long long x;

  if(sign && (sign = (num < 0)))
    x = -num;
  else
    x = num;

  i = 0;
  do {
    local_buf[i++] = digits[x % base];
  } while((x /= base) != 0);

  if(sign)
    local_buf[i++] = '-';

  while(--i >= 0) {
    if (*index < SPRINTF_BUF_MAX - 1) { 
      buf[(*index)++] = local_buf[i];
    } else {
      break; 
    }
  }
  return 0;
}

int
sprintf(char *buf, const char *fmt, ...)
{
  va_list ap;
  int i, cx, c0, c1, c2;
  char *s;
  int buf_index = 0; 

  va_start(ap, fmt);
  
  for(i = 0; (cx = fmt[i] & 0xff) != 0; i++){
    if(cx != '%'){
      if (buf_index < SPRINTF_BUF_MAX - 1) {
        buf[buf_index++] = cx;
      } else {
        break; 
      }
      continue;
    }
    i++;
    c0 = fmt[i+0] & 0xff;
    c1 = c2 = 0;
    if(c0) c1 = fmt[i+1] & 0xff;
    if(c1) c2 = fmt[i+2] & 0xff;
    
    if(c0 == 'd'){
      print_number_to_buf(va_arg(ap, int), 10, 1, buf, &buf_index);
    } else if(c0 == 'x'){
      print_number_to_buf(va_arg(ap, uint32), 16, 0, buf, &buf_index);
    } else if(c0 == 'c'){
      char c = (char)va_arg(ap, int);
      if (buf_index < SPRINTF_BUF_MAX - 1) {
        buf[buf_index++] = c;
      }
    } else if(c0 == 's'){
      if((s = va_arg(ap, char*)) == 0)
        s = "(null)";
      for(; *s; s++) {
        if (buf_index < SPRINTF_BUF_MAX - 1) {
          buf[buf_index++] = *s;
        } else {
          break;
        }
      }
    } else if(c0 == '%'){
      if (buf_index < SPRINTF_BUF_MAX - 1) {
        buf[buf_index++] = '%';
      }
    } else if(c0 == 0){
      break;
    } else {
      // 打印未知的%序列
      if (buf_index < SPRINTF_BUF_MAX - 1) {
        buf[buf_index++] = '%';
      }
      if (buf_index < SPRINTF_BUF_MAX - 1) {
        buf[buf_index++] = c0;
      }
    }
  }
  
  va_end(ap);
  
  // 确保字符串以null结尾
  if (buf_index < SPRINTF_BUF_MAX) {
    buf[buf_index] = '\0';
  } else {
    buf[SPRINTF_BUF_MAX - 1] = '\0'; 
  }
  
  return buf_index; // 返回写入的字符数（不包括null终止符）
}